package com.ruoyi.forum.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.forum.api.dto.CircleTopicListDTO;
import com.ruoyi.forum.api.vo.ReplyItem;
import com.ruoyi.forum.api.vo.TopicItem;
import com.ruoyi.forum.api.vo.UserDetail;
import com.ruoyi.forum.constant.TopicReplyTypeEnum;
import com.ruoyi.forum.constant.TopicTopStatusEnum;
import com.ruoyi.forum.domain.CircleLabel;
import com.ruoyi.forum.domain.CircleNoticeRead;
import com.ruoyi.forum.domain.CircleTopic;
import com.ruoyi.forum.domain.CircleTopicReply;
import com.ruoyi.forum.service.*;
import com.ruoyi.forum.utils.UserSessionUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: houyong
 * @date: 2025年11月17日 12:17
 */
@Tag(name = "CircleWebSiteController", description = "网站论坛前端接口")
@RestController
@RequestMapping("/circle/webSite")
public class CircleWebSiteController {

    @Autowired
    private CircleLabelService circleLabelService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CircleBlacklistService blacklistService;
    @Autowired
    private CircleTopicService circleTopicService;
    @Autowired
    private CircleTopicReplyService circleTopicReplyService;
    @Autowired
    private DozerBeanMapper mapper;
    @Autowired
    private AuthServiceExt authServiceExt;
    @Autowired
    private CircleTopicReportService circleTopicReportService;
    @Autowired
    private CircleNoticeReadService circleNoticeReadService;

    @Operation(summary = "获取话题标签列表", description = "获取话题标签列表")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", schema = @Schema(type = "int")),
            @Parameter(name = "rows", description = "条数", schema = @Schema(type = "int"))
    })
    @GetMapping(value = "/label/list")
    public AjaxResult getLabelList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer page,
                                   @RequestParam(value = "rows", defaultValue = "10", required = false) Integer rows) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleLabel::getDelFlag, 0);
// 设置排序和分页
        Page<CircleLabel> pageInfo = new Page<>(page, rows);
        pageInfo.addOrder(new OrderItem("sort_num", true)); // ASC排序
// 执行分页查询
        IPage<CircleLabel> page1 = circleLabelService.page(pageInfo, wrapper);
        return AjaxResult.success(page1);
    }

    @Operation(summary = "点赞", description = "点赞")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
    })
    @PostMapping(value = "/topic/great")
    public AjaxResult greatTopic(@RequestParam(value = "id") Long id, HttpServletRequest request) {
        try {
            UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
            if (userDetail == null) {
                return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
            }
            String uid = userDetail.getUid();
            blacklistService.checkLimit(uid);
            CircleTopic circleTopic = circleTopicService.getById(id);
            if (circleTopic == null) {
                return AjaxResult.error("对象信息不存在");
            }
            if (circleTopic.getDelFlag() != null && circleTopic.getDelFlag() == 1) {
                return AjaxResult.error("该动态已被删除！");
            }

            // 使用 LambdaQueryWrapper 构造查询条件
            LambdaQueryWrapper<CircleTopicReply> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CircleTopicReply::getDelFlag, 0)
                    .eq(CircleTopicReply::getUid, uid)
                    .eq(CircleTopicReply::getReplyType, TopicReplyTypeEnum.GREAT.value())
                    .eq(CircleTopicReply::getTopicId, circleTopic.getId());

// 执行查询
            List<CircleTopicReply> replys = circleTopicReplyService.list(wrapper);
            if (replys != null && replys.size() > 0) {
                return AjaxResult.error("操作过于频繁");
            }

            // 使用 LambdaQueryWrapper 构造查询条件
            LambdaQueryWrapper<CircleTopicReply> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(CircleTopicReply::getDelFlag, 1)
                    .eq(CircleTopicReply::getUid, uid)
                    .eq(CircleTopicReply::getReplyType, TopicReplyTypeEnum.GREAT.value())
                    .eq(CircleTopicReply::getTopicId, circleTopic.getId());

// 执行查询
            replys = circleTopicReplyService.list(wrapper2);

            if (replys == null || replys.size() == 0) {
                CircleTopicReply reply = new CircleTopicReply();
                circleTopic.setGreatNum(circleTopic.getGreatNum() + 1);
                reply.setCreateTime(System.currentTimeMillis());
                reply.setTopicId(circleTopic.getId());
                reply.setUid(uid);
                reply.setDelFlag(0);
                reply.setReplyType(TopicReplyTypeEnum.GREAT.value());
                reply.setTopFlag(0);
                if (uid.equals(circleTopic.getUid())) {
                    reply.setReadFlag(1);
                } else {
                    reply.setReadFlag(0);
                }
                reply.setTopicId(id);
                circleTopicService.great(circleTopic, reply);
            } else {
                CircleTopicReply reply = replys.get(0);
                circleTopic.setGreatNum(circleTopic.getGreatNum() + 1);
                reply.setCreateTime(System.currentTimeMillis());
                reply.setDelFlag(0);
                if (uid.equals(circleTopic.getUid())) {
                    reply.setReadFlag(1);
                } else {
                    reply.setReadFlag(0);
                }
                circleTopicService.great(circleTopic, reply);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }


    }

    @Operation(summary = "取消点赞", description = "取消点赞")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
    })
    @RequestMapping(value = "/topic/ungreat", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult ungreatTopic(@RequestParam(value = "id") Long id, HttpServletRequest request) {
        try {
            UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
            if (userDetail == null) {
                return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
            }
            String uid = userDetail.getUid();
            blacklistService.checkLimit(uid);
            CircleTopic circleTopic = circleTopicService.getById(id);
            if (circleTopic == null) {
                return AjaxResult.error("对象信息不存在");
            }
            if (circleTopic.getDelFlag() != null && circleTopic.getDelFlag() == 1) {
                return AjaxResult.error("该动态已被删除！");
            }
            circleTopic.setGreatNum(circleTopic.getGreatNum() - 1);


            // 使用 LambdaQueryWrapper 构造查询条件
            LambdaQueryWrapper<CircleTopicReply> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CircleTopicReply::getDelFlag, 0)
                    .eq(CircleTopicReply::getUid, uid)
                    .eq(CircleTopicReply::getReplyType, TopicReplyTypeEnum.GREAT.value())
                    .eq(CircleTopicReply::getTopicId, circleTopic.getId());

// 执行查询
            List<CircleTopicReply> replys = circleTopicReplyService.list(wrapper);


            if (replys != null && replys.size() > 0) {
                CircleTopicReply reply = replys.get(0);
                reply.setDelFlag(1);
                circleTopicService.ungreat(circleTopic, reply);
                return AjaxResult.success();
            } else {
                return AjaxResult.error("操作过于频繁");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }


    }

    @Operation(summary = "评论", description = "评论")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
            @Parameter(name = "content", description = "评论内容", required = true),
            @Parameter(name = "replyTo", description = "回复对象用户id"),
            @Parameter(name = "operateType", description = "0-用户回复 1-平台回复"),
            @Parameter(name = "replyId", description = "回复id")
    })
    @RequestMapping(value = "/topic/reply", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult replyTopic(@RequestParam(value = "id") Long id,
                                 @RequestParam(value = "content") String content,
                                 @RequestParam(value = "replyTo", required = false) String replyTo,
                                 @RequestParam(value = "operateType", required = false) Integer operateType,
                                 @RequestParam(value = "replyId", required = false) Long replyId, HttpServletRequest request) {
        try {
            UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
            if (userDetail == null) {
                return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
            }
            String uid = userDetail.getUid();
            blacklistService.checkLimit(uid);
            CircleTopic circleTopic = circleTopicService.getById(id);
            if (circleTopic == null) {
                return AjaxResult.error("对象信息不存在");
            }
            if (circleTopic.getDelFlag() != null && circleTopic.getDelFlag() == 1) {
                return AjaxResult.error("该动态已被删除！");
            }

            long now = System.currentTimeMillis();

            circleTopic.setReplyNum(circleTopic.getReplyNum() + 1);
            circleTopic.setLastReplyTime(now);

            CircleTopicReply reply = new CircleTopicReply();
            reply.setCreateTime(now);
            reply.setUid(uid);
            reply.setDelFlag(0);
            reply.setReplyType(TopicReplyTypeEnum.REPLY.value());
            reply.setTopFlag(0);
            reply.setContent(content);
            reply.setReplyTo(replyTo);
            if (uid.equals(circleTopic.getUid()) && StringUtils.isEmpty(replyTo)) {
                reply.setReadFlag(1);
            } else {
                if (!StringUtils.isEmpty(replyTo) && uid.equals(replyTo)) {
                    reply.setReadFlag(1);
                } else {
                    reply.setReadFlag(0);
                }
            }
            reply.setTopicId(id);
            reply.setReplyId(replyId);
            reply.setOperateType(operateType == null ? 0 : operateType);
            circleTopicService.save(circleTopic, reply);


            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());

        }
    }

    @Operation(summary = "删除我的评论", description = "删除我的评论")
    @Parameters({
            @Parameter(name = "id", description = "评论id", required = true),
    })
    @RequestMapping(value = "/topic/my/reply/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult deleteMyReply(@RequestParam(value = "id") Long id, HttpServletRequest request) {

        UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
        if (userDetail == null) {
            return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
        }
        String uid = userDetail.getUid();

        CircleTopicReply reply = circleTopicReplyService.selectById(id);
        if (reply == null) {
            return AjaxResult.error("对象信息不存在");
        }
        if (!reply.getUid().equals(uid)) {
            return AjaxResult.error("非法请求");
        }
        reply.setDelFlag(1);
        circleTopicReplyService.save(reply);

        CircleTopic circleTopic = circleTopicService.getById(reply.getTopicId());
        circleTopic.setReplyNum(circleTopic.getReplyNum() - 1);
        circleTopicService.update(circleTopic);
        return AjaxResult.success();
    }

    @Operation(summary = "获取动态点赞或回复列表", description = "获取动态点赞或回复列表")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
            @Parameter(name = "type", description = "类型 0：点赞 1：回复", required = true),
            @Parameter(name = "pageNum", description = "页码", example = "1"),
            @Parameter(name = "rows", description = "条数", example = "10")
    })
    @RequestMapping(value = "/topic/communication/list", method = RequestMethod.GET)
    public TableDataInfo getTopicCommunicationPage(@RequestParam(value = "id") Long id,
                                                   @RequestParam(value = "type") Integer type,
                                                   @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNo,
                                                   @RequestParam(value = "rows", defaultValue = "10", required = false) Integer rows) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleTopicReply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopicReply::getDelFlag, 0)
                .eq(CircleTopicReply::getTopicId, id)
                .eq(CircleTopicReply::getReplyType, type);
// 设置排序和分页
        Page<CircleTopicReply> topicReplyPage = new Page<>(pageNo, rows);
        topicReplyPage.addOrder(new OrderItem("top_flag", false), new OrderItem("create_time", false));
// 执行分页查询
        topicReplyPage = circleTopicReplyService.page(topicReplyPage, wrapper);
        List<ReplyItem> replyItemList = new ArrayList<>();
        if (topicReplyPage != null && topicReplyPage.getRecords() != null) {
            Set<String> uidSet = new HashSet<>();
            for (CircleTopicReply reply : topicReplyPage.getRecords()) {
                uidSet.add(reply.getUid());
                if (StringUtils.isNotBlank(reply.getReplyTo())) {
                    uidSet.add(reply.getReplyTo());
                }
                replyItemList.add(mapper.map(reply, ReplyItem.class));
            }
            fillReplyUserInfo(replyItemList, uidSet);
        }
        TableDataInfo result = new TableDataInfo(replyItemList, topicReplyPage.getTotal());
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("查询成功");
        return result;

    }

    /**
     * 获取相关用户资料，完善返回列表
     *
     * @param replyItemList
     * @param uidSet
     */
    private void fillReplyUserInfo(List<ReplyItem> replyItemList, Set<String> uidSet) {
        Map<String, UserDetail> userDetailMap = authServiceExt.getUserMapByUidList(Lists.newArrayList(uidSet));
        UserDetail replyUser;
        for (ReplyItem replyItem : replyItemList) {
            replyUser = userDetailMap.get(replyItem.getUid());
            replyItem.setAvatar(replyUser.getPortrait());
            replyItem.setName(replyUser.getName());

            if (StringUtils.isNotBlank(replyItem.getReplyTo())) {
                replyUser = userDetailMap.get(replyItem.getReplyTo());
                if (replyUser != null) {
                    replyItem.setReplyToName(replyUser.getName());
                }
            }
        }
    }

    @Operation(summary = "发表动态", description = "发表动态")
    @Parameters({
            @Parameter(name = "content", description = "内容"),
            @Parameter(name = "imgs", description = "图片id，以逗号隔开"),
            @Parameter(name = "labelId", description = "话题标签id", required = true)
    })
    @RequestMapping(value = "/topic/save", method = RequestMethod.POST)
    public AjaxResult saveTopic(
            @RequestParam(value = "content", required = false) String content,
            @RequestParam(value = "imgs", required = false) String imgs,
            @RequestParam(value = "labelId") String labelId, HttpServletRequest request) {

        try {
            UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
            if (userDetail == null) {
                return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
            }
            String uid = userDetail.getUid();
            blacklistService.checkLimit(uid);

            if (content == null && imgs == null) {
                return AjaxResult.error("对象信息不存在");
            }

            CircleLabel circleLabel = circleLabelService.selectById(labelId);
            if (circleLabel == null) {
                return AjaxResult.error("该板块未找到");
            }

            Map<String, Object> data = circleTopicService.addTopic(uid, content, imgs, circleLabel);

            return AjaxResult.success(data);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

    }

    @Operation(summary = "我的动态列表", description = "我的动态列表")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", example = "1"),
            @Parameter(name = "pageSize", description = "条数", example = "10")
    })
    @RequestMapping(value = "/my/topic/list", method = RequestMethod.GET)
    public AjaxResult getMyCircleTopicList(
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer rows, HttpServletRequest request) {

        UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
        if (userDetail == null) {
            return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
        }
        String uid = userDetail.getUid();
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleTopic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopic::getDelFlag, 0)
                .eq(CircleTopic::getUid, uid);

// 设置排序和分页
        Page<CircleTopic> pageInfo = new Page<>(page, rows);
        pageInfo.addOrder(new OrderItem("create_time", false)); // DESC排序

// 执行分页查询
        IPage<CircleTopic> page1 = circleTopicService.page(pageInfo, wrapper);

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setTotal(page1.getTotal());
        tableDataInfo.setRows(page1.getRecords());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return AjaxResult.success(tableDataInfo);
    }

    @Operation(summary = "删除我的动态", description = "删除我的动态")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
    })
    @RequestMapping(value = "/my/topic/delete", method = RequestMethod.POST)
    public AjaxResult deleteTopic(@RequestParam(value = "id") Long id, HttpServletRequest request) {

        UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
        if (userDetail == null) {
            return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
        }
        String uid = userDetail.getUid();

        CircleTopic circleTopic = circleTopicService.getById(id);
        if (circleTopic == null) {
            return AjaxResult.error("对象信息不存在");
        }
        if (!circleTopic.getUid().equals(uid)) {
            return AjaxResult.error("非法请求");
        }
        circleTopic.setDelFlag(1);
        circleTopicService.update(circleTopic);

        return AjaxResult.success();
    }

    @Operation(summary = "获取所有人圈子动态列表", description = "获取所有人圈子动态列表")
    @GetMapping(value = "/topic/list")
    public AjaxResult listTopic(@Parameter(hidden = true) @ModelAttribute CircleTopicListDTO dto) {
        List<CircleTopic> topicList = new ArrayList<>();
        // 第一次查询所有置顶数据
        if (dto.getCreateTime() == null) {
            topicList.addAll(listTopTopic(dto));
        }
        // 当置顶数据不够条数时使用非置顶数据填充
        Integer rows = dto.getRows() - topicList.size();
        if (rows > 0) {
            topicList.addAll(listUnTopTopic(dto, rows));
        } else {
            // 默认有一条填充
            topicList.addAll(listUnTopTopic(dto, 1));
        }
        List<TopicItem> topicItemList = convertTopicItem(dto.getUid(), topicList);
        AjaxResult result = AjaxResult.success(topicItemList);
        return result;
    }

    /**
     * 获取置顶的帖子列表
     *
     * @param dto
     * @return
     */
    private List<CircleTopic> listTopTopic(CircleTopicListDTO dto) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleTopic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopic::getDelFlag, 0)
                .eq(CircleTopic::getTopStatus, TopicTopStatusEnum.TOP.value());

        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(CircleTopic::getContent, StringEscapeUtils.unescapeHtml4(dto.getKeyword()));
        }

        if (StringUtils.isNotBlank(dto.getLableId())) {
            wrapper.eq(CircleTopic::getLableId, dto.getLableId());
        }

        // 设置排序条件
        wrapper.orderByDesc(CircleTopic::getTopStatus, CircleTopic::getTopTime);

        // 执行查询
        return circleTopicService.listTopTopic(wrapper);
    }

    /**
     * 获取非置顶的帖子列表
     *
     * @param dto
     * @param rows
     * @return
     */
    private List<CircleTopic> listUnTopTopic(CircleTopicListDTO dto, Integer rows) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleTopic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopic::getDelFlag, 0)
                .eq(CircleTopic::getTopStatus, TopicTopStatusEnum.UNTOP.value());

        if (dto.getCreateTime() != null) {
            wrapper.lt(CircleTopic::getCreateTime, dto.getCreateTime());
        }

        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(CircleTopic::getContent, StringEscapeUtils.unescapeHtml4(dto.getKeyword()));
        }

        if (StringUtils.isNotBlank(dto.getLableId())) {
            wrapper.eq(CircleTopic::getLableId, dto.getLableId());
        }

        // 设置排序
        wrapper.orderByDesc(CircleTopic::getCreateTime);

        // 执行分页查询
        Page<CircleTopic> topicPage = new Page<>(1, rows);
        return circleTopicService.page(topicPage, wrapper).getRecords();

    }

    /**
     * 转换成TopicItem列表
     *
     * @param uid
     * @param topicList
     * @return
     */
    private List<TopicItem> convertTopicItem(String uid, List<CircleTopic> topicList) {
        List<TopicItem> topicItemList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(topicList)) {
            List<String> uidList = topicList.stream().map(CircleTopic::getUid).distinct().collect(Collectors.toList());
            List<Long> topicIds = topicList.stream().map(CircleTopic::getId).distinct().collect(Collectors.toList());

            Map<Long, Long> greatStatus = circleTopicReplyService.getGreatStatus(uid, topicIds);
            for (CircleTopic circleTopic : topicList) {
                TopicItem topicItem = mapper.map(circleTopic, TopicItem.class);
                topicItem.setLabel(circleTopic.getLableName());
                topicItem.setReplyItemList(listReplyItem(uidList, circleTopic));
                topicItem.setGreatStatus(StringUtils.isEmpty(uid) ? 0 : Optional.ofNullable(Optional.ofNullable(greatStatus).orElse(new HashMap<>()).get(circleTopic.getId())).orElse(0L).intValue());
                topicItemList.add(topicItem);
            }
            fillTopicUserInfo(uidList, topicItemList, false);
        }
        return topicItemList;
    }

    /**
     * 获取帖子评论列表
     *
     * @param uidSet
     * @param circleTopic
     * @return
     */
    private List<ReplyItem> listReplyItem(List<String> uidSet, CircleTopic circleTopic) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleTopicReply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopicReply::getTopicId, circleTopic.getId())
                .eq(CircleTopicReply::getReplyType, 1)
                .eq(CircleTopicReply::getDelFlag, 0);

// 设置排序
        wrapper.orderByDesc(CircleTopicReply::getTopFlag, CircleTopicReply::getCreateTime);

// 设置分页并执行查询
        Page<CircleTopicReply> p = new Page<>(1, 3);
        List<CircleTopicReply> topicReplyList = circleTopicReplyService.page(p, wrapper).getRecords();

        List<ReplyItem> replyItemList = new ArrayList<>();
        if (topicReplyList != null) {
            replyItemList = topicReplyList.stream().map(reply -> {
                uidSet.add(reply.getUid());
                if (StringUtils.isNotBlank(reply.getReplyTo())) {
                    uidSet.add(reply.getReplyTo());
                }
                return mapper.map(reply, ReplyItem.class);
            }).collect(Collectors.toList());
        }
        return replyItemList;
    }

    /**
     * 完善发帖用户资料
     *
     * @param uidSet
     * @param topicItemList
     */
    private void fillTopicUserInfo(List<String> uidSet, List<TopicItem> topicItemList, Boolean replyVip) {
        Map<String, UserDetail> userDetailMap = authServiceExt.getUserMapByUidList(uidSet);
        UserDetail user;
        if (CollectionUtils.isNotEmpty(topicItemList)) {
            for (TopicItem topicItem : topicItemList) {
                user = userDetailMap.get(topicItem.getUid());
                topicItem.setAvatar(user.getPortrait());
                topicItem.setName(user.getName());
                topicItem.setEmail(user.getEmail());
                for (ReplyItem replyItem : topicItem.getReplyItemList()) {
                    user = userDetailMap.get(replyItem.getUid());
                    replyItem.setAvatar(user.getPortrait());
                    replyItem.setName(user.getName());
                    if (StringUtils.isNotBlank(replyItem.getReplyTo())) {
                        user = userDetailMap.get(replyItem.getReplyTo());
                        if (user != null) {
                            replyItem.setReplyToName(user.getName());
                        }
                    }
                }
            }
        }
    }

    @Operation(summary = "查询动态列表", description = "查询动态列表")
    @GetMapping(value = "/topic/search")
    public TableDataInfo searchTopic(@RequestParam String keyword,
                                     @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNo,
                                     @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleTopic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopic::getDelFlag, 0)
                .like(CircleTopic::getContent, StringEscapeUtils.unescapeHtml4(keyword));
// 设置排序和分页
        Page<CircleTopic> topicPage = new Page<>(pageNo, pageSize);
        topicPage.addOrder(new OrderItem("create_time", false)); // DESC排序
// 执行分页查询
        IPage<CircleTopic> page = circleTopicService.page(topicPage, wrapper);
        TableDataInfo result = new TableDataInfo();
        result.setTotal(page.getTotal());
        result.setRows(convertTopicItem(null, page.getRecords()));
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("查询成功");
        return result;
    }

    @Operation(summary = "获取我参与的动态列表", description = "获取我参与的动态列表")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", example = "1"),
            @Parameter(name = "pageSize", description = "条数", example = "10")
    })
    @RequestMapping(value = "/topic/ofme/list", method = RequestMethod.GET)
    public AjaxResult getTopicOfMeList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer page,
                                       @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer rows, HttpServletRequest request) {


        UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
        if (userDetail == null) {
            return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
        }
        String uid = userDetail.getUid();

        List<CircleTopic> topicList = circleTopicService.getTopicOfMe(page, rows, uid);
        if (CollectionUtils.isNotEmpty(topicList)) {
            List<Long> topicIds = topicList.stream().map(CircleTopic::getId).distinct().collect(Collectors.toList());
            circleTopicReplyService.updateReadFlag(uid, topicIds);
        }

        List<TopicItem> topicItemList = convertTopicItem(uid, topicList);
        TableDataInfo tableDataInfo = new TableDataInfo();

        tableDataInfo.setTotal(circleTopicService.getTopicOfMeCount(uid));
        tableDataInfo.setRows(topicItemList);
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return AjaxResult.success(tableDataInfo);
    }

    @Operation(summary = "获取动态详情", description = "获取动态详情")
    @Parameter(name = "id", description = "动态id", required = true)
    @RequestMapping(value = "/topic/detail", method = RequestMethod.GET)
    public AjaxResult getTopicDetail(@RequestParam(value = "id") Long id,
                                     HttpServletRequest request) {


        UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
        String uid = null;
        if (userDetail != null) {
            uid = userDetail.getUid();
        }

        CircleTopic topic = circleTopicService.getById(id);
        if (topic.getDelFlag() != null && topic.getDelFlag() == 1) {
            return AjaxResult.error("该动态已被删除！");
        }
        UserDetail data = authServiceExt.getUserDetail(topic.getUid());

        TopicItem map = mapper.map(topic, TopicItem.class);
        map.setAvatar(data.getPortrait());
        map.setName(data.getName());
        CircleLabel circleLabel = circleLabelService.selectById(topic.getLableId());
        map.setLabel(circleLabel.getName());
        map.setPhone(data.getPhone());
        if (uid == null) {
            map.setGreatStatus(0);
        } else {
            map.setGreatStatus(circleTopicReplyService.getGreatStatus(uid, topic.getId()));
        }

        return AjaxResult.success(map);
    }

    @Operation(summary = "获取动态通知数量", description = "获取动态通知数量")
    @RequestMapping(value = "/topic/notice/num/search", method = RequestMethod.GET)
    public AjaxResult getTopicUnreadNumSearch(HttpServletRequest request) {

        UserDetail user = UserSessionUtils.getUserDetail(request, redisService);
        String uid = null;
        if (user != null) {
            uid = user.getUid();
        }

        if (uid == null) {
            Map<String, Object> map = new HashMap<>();
            map.put("noticeNum", 0);
            map.put("image", "");

            return AjaxResult.success(map);
        }
        CircleNoticeRead circleNoticeRead = circleNoticeReadService.get(uid);
        if (circleNoticeRead == null) {
            circleNoticeRead = new CircleNoticeRead();
            circleNoticeRead.setReadTime(0L);
        }
        Long startTime = circleNoticeRead.getReadTime();
        Long endTime = System.currentTimeMillis();

        LambdaQueryWrapper<CircleTopicReply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopicReply::getUid, uid)
                .eq(CircleTopicReply::getDelFlag, 0)
                .eq(CircleTopicReply::getReadFlag, 0)
                .le(CircleTopicReply::getCreateTime, endTime)
                .ge(CircleTopicReply::getCreateTime, startTime);

        List<CircleTopicReply> list = circleTopicReplyService.list(wrapper);

        int maxResults = list.size();
        Map<String, Object> map = new HashMap<>();
        map.put("noticeNum", maxResults);
        map.put("image", "");

        if (list != null && maxResults > 0) {
            UserDetail userDetail = authServiceExt.getUserDetail(list.get(0).getUid());
            String image = null;
            if (userDetail != null) {
                image = userDetail.getPortrait();
            }
            map.put("image", image);
        }

        return AjaxResult.success(map);
    }

    @Operation(summary = "获取动态通知消息", description = "获取动态通知消息")
    @RequestMapping(value = "/topic/unread/list/search", method = RequestMethod.GET)
    public AjaxResult getTopicUnreadListSearch(
            @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            HttpServletRequest request) {

        UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
        if (userDetail == null) {
            return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
        }
        String uid = userDetail.getUid();

        CircleNoticeRead circleNoticeRead = circleNoticeReadService.get(uid);
        if (circleNoticeRead == null) {
            circleNoticeRead = new CircleNoticeRead();
            circleNoticeRead.setReadTime(0L);
            circleNoticeRead.setUid(uid);
        }
        Long startTime = circleNoticeRead.getReadTime();
        Long endTime = System.currentTimeMillis();
        Set<String> uidSet = new HashSet<String>();
        List<TopicItem> topicItems = circleTopicService.getTopicUnreadListSearch(uidSet, uid, startTime, endTime, page, (page - 1) * pageSize);
        List<String> uids = new ArrayList<>(uidSet);
        fillTopicUserInfo(uids, topicItems, true);
        circleNoticeRead.setReadTime(endTime);
        circleTopicReplyService.updateReadStatus(uid, circleNoticeRead);
        return AjaxResult.success(topicItems);
    }

    @Operation(summary = "举报帖子", description = "举报帖子")
    @Parameters({
            @Parameter(name = "topicId", description = "帖子id", required = true),
            @Parameter(name = "content", description = "举报内容", required = true)
    })
    @PostMapping("/topic/{topicId}/report")
    public AjaxResult reportTopic(@PathVariable Long topicId, @RequestParam String content, HttpServletRequest request) {
        try {
            UserDetail userDetail = UserSessionUtils.getUserDetail(request, redisService);
            if (userDetail == null) {
                return AjaxResult.error(HttpStatus.UNAUTHORIZED, "用户未登录");
            }
            String uid = userDetail.getUid();

            blacklistService.checkLimit(uid);
            CircleTopic topic = circleTopicService.exist(topicId);
            // 检查用户是否已经举报过该帖子
            if (circleTopicReportService.existReport(topicId, uid)) {
                return AjaxResult.error("您已举报该帖子，请勿重复操作！");
            }
            circleTopicReportService.saveReport(topic, uid, content);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error();
        }

    }


}
